package com.ffalcon.mercury.android.sdk.demo;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Pattern;

public class UrlValidator {
    private static final Pattern IP_PATTERN = Pattern.compile(
            "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");

    public static boolean isValidUrl(String urlStr) {
        try {
            // 尝试解析 URL
            URL url = new URL(urlStr);
            // 验证协议是否为 http 或者 https
            String protocol = url.getProtocol();
            if (!"http".equalsIgnoreCase(protocol) && !"https".equalsIgnoreCase(protocol)) {
                return false;
            }
            // 验证主机是否为合法的 IP 地址
            String host = url.getHost();
            if (!isValidIp(host)) {
                return false;
            }
            // 验证端口号是否在有效范围内
            int port = url.getPort();
            if (port != -1 && (port < 0 || port > 65535)) {
                return false;
            }
            return true;
        } catch (MalformedURLException e) {
            // 若解析 URL 时抛出异常，说明 URL 格式不正确
            return false;
        }
    }

    private static boolean isValidIp(String ip) {
        return IP_PATTERN.matcher(ip).matches();
    }

    public static void main(String[] args) {
        String url = "http://192.168.40.102:15038";
        boolean isValid = isValidUrl(url);
        System.out.println("URL " + url + " 是否有效: " + isValid);
    }
}